<!--
- File:    拍照识花.
-->
<template>
  <div class="Generalflower">
    <div :class="{'distinguish-bg': !imgUrl}">
      <div class="flowtop" v-if="imgUrl">
        <img :src="$config.imgsite + $config.uploadImgSrc + imgUrl + '_w640h320'">
      </div>
      <div v-else>
        <!--<img style="width: 100%; max-height: 12rem;" src="../../assets/images/shibie.png" alt="">-->
        <div style="color: #45a73a; font-size: 14px; position: absolute; top: 2.6rem; left: 8rem;margin-left: -40px; width: 80px;text-align: center;" @click="gotoWikiList">查看植物库</div>
        <!--<div class="plantbtn"><a style="margin-left: 3.5rem; margin-top: 2rem;" @click="getImg">拍照识花</a></div>-->
        <!--<div class="Generalflower2">-->
        <!--<span id="getimg"><i class="iconfont icon-paizhao" @click="getImg"></i></span>-->
        <!--</div>-->
        <div style="position: fixed; bottom: 8%; height: 70px;text-align: center; vertical-align: middle; width: 100%;">
          <span v-show="type == 'hand'" style="padding: 15px 25px; background: #5A9C5F; color: #fff; border-radius: 20px; font-size: 16px; margin-right: 10px;" @click="switchGardenSelectShow(true, 'hand')">手动添加</span>
          <span v-show="type == 'hand'" style="padding: 15px 25px; background: #5A9C5F; color: #fff; border-radius: 20px; font-size: 16px;" @click="getImg">识花添加</span>
          <span v-show="type == ''" style="padding: 15px 25px; background: #5A9C5F; color: #fff; border-radius: 20px; font-size: 16px;" @click="getImg">拍照识花</span>
        </div>
      </div>
      <div v-show="resultList.requested && resultList.data.length > 0">
        <mt-swipe :auto="0" class="banner swiper-container" style="height: 11rem" @change="handleChange">
          <mt-swipe-item class="swiper-slide" v-for="(item,index) in resultList.data" :key="index">
            <div class="flowimg" style="margin: 10px auto; height: 7.5rem; width: 7.5rem">
              <img :src="item.m_goods_image || defaultImg" alt=""/>
            </div>
            <h3 class="planttit" style="margin-top: 0">{{item.m_name}}</h3>

          </mt-swipe-item>
        </mt-swipe>
        <div class="plantbtn" v-if="currentItem" style="margin: 0 0 100px 0; padding-top: 0;">
          <div style="margin-bottom: 10px;">{{currentItem.abstract}}</div>
          <div style="text-align: center; margin-top: 20px;">
            <a @click="gotoWiki(currentItem)" style="width: 3.2rem; height: 30px;line-height: 30px; float: none; margin-right: 5px; margin-left: 0; display: inline-block">查看百科</a>
            <a @click="getImg" style="width: 3.2rem;height: 30px;line-height: 30px;float: none;margin-right: 5px; margin-left: 0;display: inline-block">重新识别</a>
            <a @click="switchGardenSelectShow(true)" style="width: 3.2rem;height: 30px;line-height: 30px;float: none;margin-right: 5px; margin-left: 0;display: inline-block">加入花园</a>
            <a @click="switchGardenSelectShow(true, 'hand')" style="width: 3.2rem;height: 30px;line-height: 30px; margin-left: 0;float: none;display: inline-block">手动添加</a>
          </div>
        </div>
        <!--<div class="plantbtn"><a style="margin-left: 3.5rem; margin-top: 1rem" @click="getImg">重新选择图片</a> </div>-->
      </div>
    </div>
    <!--<empty-data :show="resultList.requested && resultList.data.length <= 0" text="未能识别该图片" style="margin-top: 2rem"></empty-data>-->
    <div class="Cart_nodata" v-show="resultList.requested && resultList.data.length <= 0">
      <i class="iconfont icon-kong"></i>
      <p>未能识别该图片</p>
      <a href="javascript:void(0)" style="width: 140px" @click="getImg">重新选择图片</a>
      <a href="javascript:void(0)" style="width: 140px; margin-top: 20px;" @click="switchGardenSelectShow(true, 'hand')">手动添加</a>
    </div>
    <!--<ul>-->
    <!--<li style="line-height: 20px; width: 100%; height: 20px;text-align: center; float: none">{{garden.moodGarden.garden_name}}</li>-->
    <!--<li style="width: 100%" v-for="item in garden.myGarden">{{item.garden_name}}</li>-->
    <!--</ul>-->
    <div v-if="gardenSelectShow" style="width: 100%; clear: both;">
      <div class="PopBg" @click="switchGardenSelectShow(false)"></div>
      <ul class="AttributeSelectionPop" style="width: 70%; max-height:50%;overflow:auto; left: 15%; top: 25%;">
        <li class="garden-select-item" style="font-weight: bold">选择加入的花园</li>
        <li class="garden-select-item" @click="addToGarden(item)" v-for="item in garden">
          <template v-if="item.sg_id != '0'">{{item.sg_name}}-</template>
          {{item.garden_name}}
          <template v-if="item.sg_id != '0'">(共享)</template>
        </li>
      </ul>
    </div>
    <div id="select-pic">
      <input type="file" id="fileInput1" accept="image/jpeg,image/jpg,image/png,image/gif" style="display: none" @change="fileSelected">
    </div>
    <mt-actionsheet
      :actions="actions"
      v-model="sheetVisible"
    >
    </mt-actionsheet>
    <footer-tab></footer-tab>
  </div>
</template>

<script>
  import {Swipe, SwipeItem, Actionsheet} from 'mint-ui'
  import {bodyWhiteBg} from '../../mixin'

  export default{
    mixins: [bodyWhiteBg],
    data() {
      return {
        type: this.$route.query.type || '', // 'hand' 手动添加植物，默认为识花
        temp: this.$route.query.temp,
        imgUrl: null, // 当前要识别的图片地址（上传到服务器后的地址）
        garden: {moodGarden: null, myGarden: []},
        selectedGardenId: '',
        gardenSelectShow: false,
        defaultImg: require('../../assets/images/demo/xinqing2.png'),
        resultList: {requested: false, data: []},
        currentItem: null, // 结果里的当前项
        sheetVisible: false,
        addType: '', // 'hand' 手动添加， 默认为拍照识花添加
        actions: [{
          name: '拍照',
          method: this.getFromCamera
        }, {
          name: '从相册选取',
          method: this.getFromAlbum
        }]
      }
    },
    components: {
      'mtSwipe': Swipe,
      'mtSwipeItem': SwipeItem,
      'mt-actionsheet': Actionsheet
    },
    beforeRouteLeave  (to, from, next) {
      this.$indicator.close()
      next()
    },
    created() {
      console.log('create', this.$route.meta.keepAlive)
//      this.$native.weixinShare(window.location.href, '扫码识花')
      this.getGardenList()
      // this.$native.weixinShare(window.location.href)
    },
    mounted() {
      this.$native.weixinShare(window.location.href, '遇花园', null, '拍照识花 发现身边的美丽')
//      setTimeout(() => {
//        console.log('type', this.type)
//
//      }, 500)
//      this.getImg()
    },
    watch: {
      $route(to) {
//        this.imgUrl = null // 当前要识别的图片地址（上传到服务器后的地址）
//        this.selectedGardenId = ''
//        this.gardenSelectShow = false
//        this.resultList = {requested: false, data: []}
//        this.currentItem = null // 结果里的当前项
//        this.sheetVisible = false
//        this.getImg()
        if (to.name == 'distinguish') {
          console.log(to.query.temp, this.temp)
          if (to.query.temp != this.temp) {
            this.initData()
          }
        }
      }
    },
    methods: {
      initData() {
        this.getGardenList()
        this.type = this.$route.query.type || ''
        console.log('type', this.type)
        if (this.type == 'hand') {
          this.$utils.setWechatTitle('添加植物')
        } else {
          this.$utils.setWechatTitle('识花')
        }
        this.imgUrl = null // 当前要识别的图片地址（上传到服务器后的地址）
        this.selectedGardenId = ''
        this.gardenSelectShow = false
        this.resultList = {requested: false, data: []}
        this.currentItem = null // 结果里的当前项
        this.sheetVisible = false
      },
      gotoBaiduBaike(url) {
        this.$router.push({name: 'wiki-baidu', query: {url: url}})
//        if (this.deviceType == 'Android' || this.deviceType == 'iPhone') {
//          if (plus) { // eslint-disable-line
//            plus.runtime.openURL(url) // eslint-disable-line
//          } else {
//            console.log('plus not define')
//          }
//        } else {
//          window.location.href = url
//        }
      },
      gotoWikiList() {
        this.$router.push({name: 'wiki-list'})
      },
      gotoWiki(plant) {
        if (plant.m_id) {
          this.$router.push({name: 'wiki', query: {id: plant.m_id}})
        } else {
//          this.$router.push({name: 'wiki-baidu', query: {url: plant.baike}})
          window.location.href = plant.baike
        }
      },
      async switchGardenSelectShow(boolValue, type) {
        if (boolValue) {
          let auth = this.$storage.getAuthed()
          if (!auth || auth == 'null') {
            let authStatus = await this.$request.getAuth()
            if (authStatus != '1') { // 未注册过需先注册才能加入花园
              this.$router.push({name: 'member-register'})
              return
            }
          }
        }
        if (type) {
          this.addType = type
        }
        this.gardenSelectShow = boolValue
      },
      distinguish() {
        this.$indicator.open('识别中...')
        let imgUrl = this.$config.imgsite + this.$config.uploadImgSrc + this.imgUrl + '_w640'
        this.$request.distinguish(imgUrl).then(result => {
          this.resultList.data = result
          if (result.length > 0) {
            this.currentItem = result[0]
          }
        }).finally(() => {
          this.$indicator.close()
          this.resultList.requested = true
        })
      },
      handleChange(index) {
        this.currentItem = this.resultList.data[index]
        this.gardenListVisible = false
      },
      getGardenList() {
        this.$request.getAllGardenList().then(data => {
          this.garden = data
        }).catch(e => {})
      },
      addToGarden(garden) {
        let gardenType = garden.sg_id == '0' ? this.$dictionary.gardenType.private : this.$dictionary.gardenType.share
        if (this.addType == 'hand') {
          this.$router.push({
            name: 'plant-add',
            query: {garden: garden.g_id, gardenType: gardenType, parentId: garden.sg_id}
          })
        } else {
          if (this.currentItem.m_id) { // 植物库里有该植物
            this.$router.push({
              name: 'plant-attr',
              query: {
                garden: garden.g_id,
                plant: this.currentItem.m_id,
                plantName: this.currentItem.m_name,
                image: this.imgUrl
              }
            })
          } else {
            this.$router.push({
              name: 'plant-add',
              query: {
                garden: garden.g_id,
                gardenType: gardenType,
                parentId: garden.sg_id,
                plantName: this.currentItem.m_name,
                baidu: this.currentItem.baike,
                img: this.imgUrl
              }
            })
          }
        }
      },
      getImg() {
        let deviceType = this.$utils.getDeviceType()
        if (deviceType == 'wx-iPhone' || deviceType == 'wx-Android') {
          wx.chooseImage({ // eslint-disable-line
            count: 1, // 默认9
            sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
            sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
            success: (res) => {
              var localId = res.localIds[0]
              wx.getLocalImgData({ // eslint-disable-line
                localId: localId,
                success: (res) => {
                  var localData = res.localData
                  localData = localData.replace('jgp', 'jpeg')
                  if (localData.indexOf('data:image/jpeg;base64,') == -1) {
                    localData = 'data:image/jpeg;base64,' + localData
                  }
                  this.$indicator.open('上传图片中...')
                  this.$request.uploadTmpImg(localData).then(data => {
                    this.imgUrl = data.image
                    this.distinguish()
                  }).catch(e => {
                    this.$toast('上传图片失败:' + e.msg)
                  }).finally(() => {
                    this.$indicator.close()
                  })
                }
              })
            }
//            cancel: () => {
//              console.log('user cancle')
//              this.$router.go(-1)
//            }
          })
        } else if (deviceType == 'iPhone') {
          this.getFromAlbum() // 因为iphone不带capture属性的input 点击后本身就会弹出选择图库或拍照
        } else {
          this.sheetVisible = true
        }
      },
      getFromCamera() {
        var imgInputFile = document.getElementById('fileInput1')
        if (!imgInputFile.hasAttribute('capture')) {
          imgInputFile.setAttribute('capture', 'camera')
        }
        this.$utils.clickFileInput(imgInputFile)
        console.log('getFromCamera')
      },
      getFromAlbum() {
        var imgInputFile = document.getElementById('fileInput1')
        if (imgInputFile.hasAttribute('capture')) {
          imgInputFile.removeAttribute('capture')
        }
        this.$utils.clickFileInput(imgInputFile)
        console.log('getFromAlbum')
      },
      clearInputFile() {
        var self = this
        var selectPic = document.getElementById('select-pic')
        var randomStr = Math.random().toString(36)
        selectPic.innerHTML = '<input id="fileInput1" type="file" title="" ' + randomStr + '"  accept="image/jpeg,image/jpg,image/png,image/gif"  id="fileInput1" style="visibility: hidden" >'
        document.getElementById('fileInput1').addEventListener('change', self.fileSelected)
      },
      fileSelected(e) {
        console.log('触发了input 的 change事件')
        try {
          var reader = new window.FileReader()
          reader.onload = (e) => {
            if (e.total > 1024 * 1024 * 5) {
              this.$toast('图片大小不能超过5M')
              return
            }
            // 调用图片压缩方法
            console.log('成功加载图片，开始压缩图片...')
            this.$utils.compress(e.target.result, (imgDataUrl) => {
              this.$request.uploadTmpImg(imgDataUrl).then(data => {
                this.imgUrl = data.image
                this.distinguish()
              }).catch(e => {
                this.$toast('上传图片失败:' + e.msg)
              })
            })
          }
          // 选取同名文件不会再次触发change事件，所以在加载后替换input控件
          reader.onloadend = (e) => {
            this.clearInputFile()
          }
          reader.readAsDataURL(e.target.files[0])
        } catch (e) {
          console.log('读取图片文件发生了错误')
          console.log(e)
        }
      }
    }
  }
</script>

<style>
  .distinguish-bg {
    position: fixed;
    width: 100%;
    height: 100%;
    background: url(../../assets/images/shihuabg.jpg) center top no-repeat;
    background-size: 100%;
  }

  .Generalflower2 {
    width: 120px;
    text-align: center;
    height: 120px;
    position: fixed;
    bottom: 8%;
    left: 50%;
    margin-left: -60px;
    text-align: center;
    background: url(../../assets/images/Photograph_bg.png) no-repeat;
    background-size: cover;
  }

  .Generalflower2 i {
    display: block;
    line-height: 120px;
    font-size: 40px;
    text-align: center;
    color: #fff;
  }

  .garden-select-item {
    line-height: 40px;
    width: 100%;
    height: 40px;
    text-align: center;
    float: none;
    background-color: white;
    z-index: 9999999;
    border-bottom: 1px solid #eee;
    font-size: 14px;
  }
</style>
